/*
 pledge.go
 Created by hupfei on 2019-08-16
*/

package v1

import (
	"github.com/gin-gonic/gin"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/app/middleware"
	"zimuzu_cvn_web_api/service"
)

type PledgeAPI struct {
}

func (a PledgeAPI) Name() string {
	return "pledge API"
}

func (a PledgeAPI) Bind() {
	pledgeAuthAPI := config.C.Router.Group("/v1/app/pledge", middleware.TrackLog(), middleware.AuthMiddleware())
	{
		pledgeAuthAPI.GET("pledging", pledging)
		pledgeAuthAPI.GET("draw", draw)
	}
}

/*
 * @ Author: hupfei
 * @ Description: 3.9.3 质押
 **/
type pledgeParams struct {
	Cvnt   float64 `form:"cvnt" binding:"required"`
	Source int     `form:"source" binding:"required"`
	U      string  `form:"u"`
}

func pledging(c *gin.Context) {

	var params pledgeParams
	err := c.ShouldBindQuery(&params)
	if err != nil || params.Cvnt < 0 {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	if params.Source != 5 {
		api.SendResponse(c, errno.ServiceOffErr, nil)
		return
	}

	// 校验u
	if params.U != "" {
		ok := service.IsPayPasswordChecked(uid, params.U)
		if !ok {
			api.SendResponse(c, errno.SignError, nil)
			return
		}
	}

	err = service.Pledge(uid, params.Cvnt, params.Source)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}
	errno.OK.Info = "质押成功"
	api.SendResponse(c, errno.OK, nil)
	return
}

/*
 * @ Author: hupfei
 * @ Description: 3.9.4 质押提取
 **/
func draw(c *gin.Context) {

	var params pledgeParams
	err := c.ShouldBindQuery(&params)
	if err != nil || params.Cvnt < 0 {
		api.SendResponse(c, errno.ParamsError, nil)
		return
	}
	if params.Source != 5 {
		api.SendResponse(c, errno.ServiceOffErr, nil)
		return
	}

	uid, _ := service.GetUserIdByRequest(c)
	source := model.PledgeRouter
	errno.OK.Info = "质押CVNT已成功提取，提取的CVNT将会被锁仓24小时！"
	if params.Source == 5 {
		errno.OK.Info = "质押CVNT已成功提取，提取的CVNT将会在1~5分钟内到账！"
		source = model.PledgeDeposit
	}

	// 校验u
	if params.U != "" {
		ok := service.IsPayPasswordChecked(uid, params.U)
		if !ok {
			api.SendResponse(c, errno.SignError, nil)
			return
		}
	}

	err = service.DrawTask(uid, 0, params.Cvnt, source)
	if err != nil {
		api.SendResponse(c, err, nil)
		return
	}

	api.SendResponse(c, errno.OK, nil)
	return
}
